package com.srit.core.bean;

import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 返回页面文字封装
 * 
 * @author guan
 * 
 */
public class PageMsg {
	static Logger log = LoggerFactory.getLogger(PageMsg.class);
	public static final String ERROR_EXIST = "{}记录已经存在!";
	public static final String SUCC_SAVE = "{}保存成功!";
	public static final String SUCC_UPDATE = "{}修改成功!";
	public static final String SUCCESS_KEY = "success";
	public static final String MESSAGE_KEY = "message";
	public static final String MARK_KEY = "mark";
	private Map JSONmap;
	{
		JSONmap = new HashMap();
		JSONmap.put(SUCCESS_KEY, false);
	}

	public void setSuccessMsg(String format, Object obj) {
		String tmp = loadMessage(format, obj);
		setMessage(tmp);
		setSuccess(true);
	}

	public void setErrorMsg(String format, Object obj) {
		String tmp = loadMessage(format, obj);
		setMessage(tmp);
		setSuccess(false);
	}

	public void setSuccessMsg(String value) {
		setMessage(value);
		setSuccess(true);
	}

	public void setErrorMsg(String value) {
		setMessage(value);
		setSuccess(false);
	}

	public void setSuccessMsg(String format, Object[] objs) {
		String tmp = loadMessage(format, objs);
		setMessage(tmp);
		setSuccess(true);
	}

	public void setErrorMsg(String format, Object[] objs) {
		String tmp = loadMessage(format, objs);
		setMessage(tmp);
		setSuccess(false);
	}

	private void setMessage(String message) {
		this.JSONmap.put(MESSAGE_KEY, message);
	}

	private void setSuccess(boolean success) {
		this.JSONmap.put(SUCCESS_KEY, success);
	}

	private String loadMessage(String format, Object[] objs) {
		if (objs.length == 0) {
			return format;
		} else {
			int i = 0;
			while (format.indexOf("{}") != -1) {
				if (i == objs.length) {
					break;
				}
				format = loadMessage(format, objs[i]);
				i++;
			}
			return format;
		}
	}

	private String loadMessage(String format, Object obj) {
		if (format.indexOf("{}") != -1) {
			return format.replaceFirst("\\{}", obj.toString());
		} else {
			return format;
		}
	}

	public void setMark(String mark) {
		this.JSONmap.put(MARK_KEY, mark);
	}

	public void setDataToJSONMap(String key, Object value) {
		this.JSONmap.put(key, value);
	}

	public Map getMap() {
		return JSONmap;
	}

	public String getJSON() {
		try {
			return JSONUtil.serialize(JSONmap);
		} catch (JSONException e) {
			e.printStackTrace();
			return "";
		}
	}
}
